package tw.edu.tku.im.maze.database;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import tw.edu.tku.im.maze.Packet;
import tw.edu.tku.im.maze.RegisterRep;
import tw.edu.tku.im.maze.RegisterReq;

public class RegisterProcessor extends PacketProcessor {

   @Override
   String acceptName() {
      return "register";
   }

   @Override
   Packet process(Packet packet) {
      RegisterReq req = (RegisterReq)packet;
      String userId = req.getUserID().trim();
      String name = req.getName().trim();
      String password = req.getPassword().trim();
      final int idPasswordLength = 18;
      final int nameLength = 10;
      if(userId.length()>idPasswordLength) { return new RegisterRep(2); }
      if(name.length()>nameLength) { return new RegisterRep(3); }
      if(password.length()>idPasswordLength){ return new RegisterRep(4); }
      
      try {
         Connection con = DriverManager.getConnection(address,user,passwd);
         con.setCatalog(database);
         CallableStatement cstmt = con.prepareCall("{call usp_loginCheck(?)}"); 
         cstmt.setString(1, userId);
         cstmt.execute();
         ResultSet rs = cstmt.getResultSet();
         if(rs.next()) { return new RegisterRep(1); }
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         String dateString = sdf.format(new Date());
         int ticket = dateString.hashCode();
         RegisterRep rep = new RegisterRep(0, userId, name, ticket);
         cstmt = con.prepareCall("{call usp_register(?, ?, ?, ?, ?)}");
         cstmt.setString(1, userId);
         cstmt.setString(2, name);
         cstmt.setString(3, password);
         cstmt.setInt(4, ticket);
         cstmt.setString(5, dateString);
         cstmt.execute();
         return rep;
      } catch (SQLException e) {
         e.printStackTrace();
      }
      
      return new RegisterRep(5);
   }

}
